package com.xjy.controller;

import com.github.pagehelper.PageInfo;
import com.xjy.pojo.*;
import com.xjy.service.cartService;
import com.xjy.service.orderService;
import com.xjy.service.pathService;
import com.xjy.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
/*@RequestMapping("/user")*/
public class userController {
    //controller调service
    @Autowired
    @Qualifier("userServiceImpl")
    private userService userService;
    @Autowired
    @Qualifier("cartServiceImpl")
    private cartService cartService;
    @Autowired
    @Qualifier("pathServiceImpl")
    private pathService pathService;
    @Autowired
    @Qualifier("orderServiceImpl")
    private orderService orderService;


/*    //查询全部user并返回到展示页面
    @RequestMapping("/allUser")
    public String listUser(Model model){
        List<User> users = userService.getUsers();

        model.addAttribute("list",users);
        return "allUser";
    }*/
    @RequestMapping("/user/toLoginPage")
    public String toLoginPage(){
        return "login";
    }

    @RequestMapping("/user/login")
    public String login(String username, String password, Model model, HttpSession session){
        User user = userService.getUserByName(username);
        System.out.println(password);
        System.out.println(user.getPwd());
         if (user != null) {
             System.out.println(user.getPwd().equals(password));
             if (user.getPwd().equals(password)) {
                 session.setAttribute("loginInfo",user);
                 /*System.out.println(session.getAttribute("loginInfo"));*/
                 return "main";
             }else {
                 model.addAttribute("loginError","密码输入错误");
                 return "login";
             }

         }else {
             model.addAttribute("loginError","该用户不存在");
             return "login";
         }
    }

    @RequestMapping("/user/loginOut")
    public String loginOut(HttpSession session){
        session.removeAttribute("loginInfo");
        return "login";
    }

    //跳转到增加页面
    @RequestMapping("/user/toAddPage")
    public String toAddPage(){
        return "jsp/addUser";
    }

    //添加用户请求
    @RequestMapping("/user/addUser")
    public String addUser(User user) {
        System.out.println("adduser=>"+user);
        userService.userRegister(user);
        //重定向到@RequestMapping("/allUser")请求
        return "redirect:/user/toLoginPage";
    }

    //跳转到增加页面
    @RequestMapping("/user/toUpdatePage")
    public String toUpadtePage(int uid,Model model){
        User user= userService.getUserById(uid);
        model.addAttribute("Guser",user);

        return "jsp/updateUser";
    }

    //修改用户信息请求
    @RequestMapping("/user/updateUser")
    public String updateUser(User user) {
        System.out.println("updateUser=>"+user);
        userService.userUpdate(user);
        //重定向到@RequestMapping("/allUser")请求
        return "redirect:/user/userInfo";
    }


    //添加购物车
    @RequestMapping("/user/addCart")
    public String addCart(String pid,HttpSession session){
        User user = (User) session.getAttribute("loginInfo");
        Path path =pathService.getPathById(pid);
        Cart cart =cartService.getExistCart(user.getUid(),pid);
        if (cart == null) {
            String cid = UUID.randomUUID().toString().replaceAll("-","");
            cart = new Cart(cid,user.getUid(),path,1);
            System.out.println("addCart===>"+cart);
            cartService.addCart(cart);
        }else {
            cartService.updateCart(cart.getCid(),cart.getNum()+1);
        }
        return "redirect:/user/allCart";
    }

    //所有购物车
    @RequestMapping("/user/allCart")
    public String allCart(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,HttpSession session,Model model){
        User user =(User) session.getAttribute("loginInfo");
        List<Cart> cartList = cartService.getCartList(user.getUid(),page,size);
        PageInfo cartInfo = new PageInfo(cartList);
        model.addAttribute("cartList",cartInfo);
        return "jsp/allCart";

    }

    //删除
    @RequestMapping("/user/deleteCart")
    public String deleteCart(String cid){
        System.out.println("deleteCart===>"+cid);
        cartService.deleteCart(cid);
        return "redirect:/user/allCart";
    }

    //前往支付页面
    @RequestMapping("/user/toAddOrder")
    public String toAddOrder(String pid,Model model){
        Path path =pathService.getPathById(pid);
        model.addAttribute("pathInfo",path);
        return "jsp/addOrder";
    }

    //添加订单
    @RequestMapping("/user/addOrder")
    public String addOrder(String pid, int num, float total, String startDate,HttpSession session,HttpServletResponse response,Model model) throws ParseException, IOException {
        PrintWriter out = null;
        response.setContentType("text/html; charset=UTF-8"); //转码
        out = response.getWriter();

        if (num <= 0) {
            out.write("<script>");
            out.write("alert('数量错误，请重新下单');");
            out.write("location.href='/back_war_/user/toAddOrder?pid="+pid+"'");
            out.write("</script>");
            out.close();
            return null;
        }
        if (num > 30) {
            out.write("<script>");
            out.write("alert('对不起，最多三十人，请重新下单');");
            out.write("location.href='/back_war_/user/toAddOrder?pid="+pid+"'");
            out.write("</script>");
            out.close();
            return null;
        }

        String oid = UUID.randomUUID().toString().replaceAll("-","");
        Date createDate = new Date();
        User user = (User) session.getAttribute("loginInfo");
        int uid = user.getUid();
        Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(startDate+" 00:00:00");
        if (date.getTime() < createDate.getTime()){
            out.write("<script>");
            out.write("alert('时间错误，请重新下单');");
            out.write("location.href='/back_war_/user/toAddOrder?pid="+pid+"'");
            out.write("</script>");
            out.close();
            return null;
        }
        Order order = new Order(oid,uid,pid,num,total,createDate,date,0);
        System.out.println("addOrder===>"+order);
        orderService.addOrder(order);
        Path path =pathService.getPathById(pid);
        model.addAttribute("pathInfo",path);
        model.addAttribute("orderInfo",order);
        return "jsp/pay";

    }

    @RequestMapping("/user/toPay")
    public String toPay(String oid,Model model){
        Order order = orderService.getOrderById(oid);
        Path path =pathService.getPathById(order.getPid());
        model.addAttribute("pathInfo",path);
        model.addAttribute("orderInfo",order);
        return "jsp/pay";
    }

    @RequestMapping("/user/pay")
    public String pay(String oid,Model model){
        orderService.updateOrder(oid,1);
        Order order = orderService.getOrderById(oid);
        model.addAttribute("order",order);
        List<OrderInfo> orderInfos = new ArrayList<>();
        for (int i = 0; i < order.getNum();i++){
            String orid = UUID.randomUUID().toString().replaceAll("-","");
            OrderInfo orderInfo = new OrderInfo(orid,oid);
            orderInfos.add(orderInfo);
            orderService.addOrderInfo(orderInfo);
        }
        PageInfo orderInfo = new PageInfo(orderInfos);
        model.addAttribute("orderInfos",orderInfo);
        return "jsp/allOrderInfo";
    }

    @RequestMapping("/user/allOrderInfo")
    public String allOrderInfo(String oid,Model model){
        //获取订单信息与订单内置信息，加入model
        Order order = orderService.getOrderById(oid);
        model.addAttribute("order",order);
        List<OrderInfo> orderInfos = orderService.getOrderInfos(oid);
        PageInfo orderInfo = new PageInfo(orderInfos);
        model.addAttribute("orderInfos",orderInfo);
        return "jsp/allOrderInfo";
    }

    @RequestMapping("/user/toUpdateOrderInfo")
    public String toUpdateOrderInfo(String orid,Model model){
        OrderInfo orderInfo = orderService.getOrderInfoById(orid);
        model.addAttribute("orderInfo",orderInfo);
        return "jsp/updateOrderInfo";
    }

    @RequestMapping("/user/updateOrderInfo")
    public String updateOrderInfo(String orid,
                                  String oid,
                                  String IDnumber,
                                  int tel,
                                  MultipartFile healthCode,
                                  MultipartFile tourCode,
                                  HttpServletRequest request, RedirectAttributes attr) throws IOException {


        OrderInfo orderInfo = orderService.getOrderInfoById(orid);
        File targetFile,realPath;
        File[] files;
        String healthName=orderInfo.getHealthCode();
        String tourName = orderInfo.getTourCode() ;

        System.out.println("orderInfo===>"+orderInfo);
        System.out.println(orderInfo.getHealthCode()==null);

        //如果健康码与行程码文件为空,不需要up
        if (healthCode.isEmpty()) {
            System.out.println("不上传文件");
        }else {
            String healthPath =request.getServletContext().getRealPath("/healthCode");
            //获取上传文件的路径
            realPath =new File(healthPath);
            if (!realPath.exists()) {
                realPath.mkdirs();
            }
            //如果原先有文件，需要删除源文件
            if (!(orderInfo.getHealthCode() == null)){
                healthName = UUID.randomUUID().toString().replaceAll("-","")+healthCode.getOriginalFilename();
                System.out.println("删除文件");
                files = realPath.listFiles();
                for (int i = 0; i < files.length; i++) {
                    //当该文件的名字和我们从数据库中查到的名字相同时删除
                    if (files[i].getName().equals(orderInfo.getHealthCode())){
                        files[i].delete();
                    }
                }
            }
            //上传文件地址
            System.out.println("上传文件保存地址："+realPath);
            //封装上传文件位置的全路径
            targetFile = new File(healthPath,healthName);
            //通过CommonsMultipartFile的方法直接写文件
            healthCode.transferTo(targetFile);

        }

        //如果健康码与行程码文件为空,不需要up
        if (tourCode.isEmpty()) {
            System.out.println("不上传文件");
        }else {
            String tourPath =request.getServletContext().getRealPath("/tourCode");
            tourName = UUID.randomUUID().toString().replaceAll("-","")+tourCode.getOriginalFilename();
            //获取上传文件的路径
            realPath =new File(tourPath);
            if (!realPath.exists()) {
                realPath.mkdirs();
            }
            //如果原先有文件，需要删除源文件
            if (!(orderInfo.getTourCode() == null)){
                System.out.println("删除文件");
                files = realPath.listFiles();
                for (int i = 0; i < files.length; i++) {
                    //当该文件的名字和我们从数据库中查到的名字相同时删除
                    if (files[i].getName().equals(orderInfo.getTourCode())){
                        files[i].delete();
                    }
                }
            }
            //上传文件地址
            System.out.println("上传文件保存地址："+realPath);
            //封装上传文件位置的全路径
            targetFile = new File(tourPath,tourName);
            //通过CommonsMultipartFile的方法直接写文件
            tourCode.transferTo(targetFile);

        }


        orderInfo.setIDnumber(IDnumber);
        orderInfo.setTel(tel);
        orderInfo.setHealthCode(healthName);
        orderInfo.setTourCode(tourName);

        orderService.updateOrderInfo(orderInfo);

        attr.addAttribute("orid",orid);
        return "redirect:/user/toUpdateOrderInfo";
    }

    @RequestMapping("/user/allOrder")
    public String allOrder(HttpSession session,Model model){
        User user = (User) session.getAttribute("loginInfo");
        List<Map> orders = orderService.getOrdersByUid(user.getUid());
        /*0->待付款；1->待审核；2->行程开始；3->已完成；4->已评论；5->已关闭；6->无效订单。*/
        List<Map> noPay=new ArrayList<>();
        List<Map> noReview=new ArrayList<>();
        List<Map> noStart=new ArrayList<>();
        List<Map> noCompleted=new ArrayList<>();
        List<Map> noComment=new ArrayList<>();
        List<Map> closed=new ArrayList<>();
        List<Map> invalid=new ArrayList<>();

        int status;
        for (Map order : orders) {
             status=(int) order.get("status");
            if (status==0) {
                noPay.add(order);
            }else if (status == 1) {
                noReview.add(order);
            }else if (status== 2) {
                noStart.add(order);
            }else if (status== 3) {
                noCompleted.add(order);
            }else if (status== 4) {
                noComment.add(order);
            }else if (status== 5) {
                closed.add(order);
            }else {
                invalid.add(order);
            }
        }
        PageInfo noPayPageInfo = new PageInfo(noPay);
        model.addAttribute("noPay",noPayPageInfo);
        PageInfo noReviewPageInfo = new PageInfo(noReview);
        model.addAttribute("noReview",noReviewPageInfo);
        PageInfo noStartPageInfo = new PageInfo(noStart);
        model.addAttribute("noStart",noStartPageInfo);
        PageInfo noCompletedPageInfo = new PageInfo(noCompleted);
        model.addAttribute("noCompleted",noCompletedPageInfo);
        PageInfo noCommentPageInfo = new PageInfo(noComment);
        model.addAttribute("noComment",noCommentPageInfo);
        PageInfo closedPageInfo = new PageInfo(closed);
        model.addAttribute("closed",closedPageInfo);

        return "jsp/allOrder";
    }

    @RequestMapping("/user/deleteOrder")
    public String deleteOrder(String oid,HttpServletResponse response) throws IOException {
        PrintWriter out = null;
        response.setContentType("text/html; charset=UTF-8"); //转码
        out = response.getWriter();

        Order order = orderService.getOrderById(oid);
        if (order.getStatus()>2) {
            out.write("<script>");
            out.write("alert('订单已经开始，无法删除');");
            out.write("location.href='/back_war_/user/allOrder'");
            out.write("</script>");
            out.close();
            return null;
        }
        System.out.println("deleteOrder===>"+order);
        orderService.deleteOrder(oid);
        orderService.deleteOrderInfo(oid);

        return "redirect:/user/allOrder";
    }

    @RequestMapping("/user/toComment")
    public String toComment(String oid,Model model,HttpServletResponse response) throws IOException {
        Order order = orderService.getOrderById(oid);
        if(order.getStatus()==4){
            model.addAttribute("order",order);
            return "jsp/addComment";
        }else {
            PrintWriter out = null;
            response.setContentType("text/html; charset=UTF-8"); //转码
            out = response.getWriter();
            out.write("<script>");
            out.write("alert('订单未结束，无法评论');");
            out.write("location.href='/back_war_/user/allOrder'");
            out.write("</script>");
            out.close();
            return null;
        }

    }

    @RequestMapping("/user/toAddComment")
    public String toAddComment(String oid,Model model){
        Order order = orderService.getOrderById(oid);
        model.addAttribute("order", order);
        return "jsp/addComment";
    }

    @RequestMapping("/user/addComment")
    public String addComment(String oid, HttpSession session,String comm,MultipartFile[] files,HttpServletRequest request) throws IOException {
        User user = (User) session.getAttribute("loginInfo");
        String picid = UUID.randomUUID().toString().replaceAll("-","");
        String pid = orderService.getOrderById(oid).getPid();
        Comment comment =new Comment(oid,comm,picid,pid);
        orderService.addComment(comment);

        Path path =pathService.getPathById(pid);
        path.setNum(path.getNum()+1);
        pathService.updatePath(path);

        //上传图片
        String filePath =request.getServletContext().getRealPath("/comment");
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName ;
        for (int i = 0; i < files.length; i++){
            if(!files[i].isEmpty()){
                fileName = UUID.randomUUID().toString().replaceAll("-","")+files[i].getOriginalFilename();
                File targetFile = new File(filePath,fileName);
                files[i].transferTo(targetFile);
                orderService.addPics(picid,fileName);
            }
        }
        orderService.updateOrder(oid,5);

        return "redirect:/user/allOrder";
    }

    @RequestMapping("/user/toUpdateComment")
    public String toUpdateComment(String oid,Model model){
        Comment comment =orderService.getComment(oid);
        //使评论的图片总数为3
        for (int i = 0; i < 3-comment.getPics().size(); i++) {
            comment.getPics().add(null);
        }
        System.out.println("getComment===>"+comment);
        model.addAttribute("comment",comment);
        return "jsp/updateComment";
    }

    @RequestMapping("/user/updateComment")
    public String updateComment(String oid,String comm, RedirectAttributes attr){
        Map<String, String> map = new HashMap<>();
        map.put("oid",oid);
        map.put("comm",comm);
        orderService.updateComment(map);
        //跳转地址带上oid参数
        attr.addAttribute("oid", oid);
        return "redirect:/user/toUpdateComment";

    }

    @RequestMapping("/user/updateCommPic")
    public String updateCommPic(String oid, String picid, String oldPic, MultipartFile newPicture, HttpServletRequest request, HttpServletResponse response, RedirectAttributes attr) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("picid",picid);
        map.put("oldPic",oldPic);

        String filePath =request.getServletContext().getRealPath("/comment");
        File realPath = new File(filePath);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        String  fileName = UUID.randomUUID().toString().replaceAll("-","")+newPicture.getOriginalFilename();;
        File targetFile = new File(filePath,fileName);
        newPicture.transferTo(targetFile);
        map.put("newPic",fileName);
        orderService.updatePics(map);

        System.out.println("删除文件");
        File[] files = realPath.listFiles();
        for (int i = 0; i < files.length; i++) {
            //当该文件的名字和我们从数据库中查到的名字相同时删除
            if (files[i].getName().equals(oldPic)){
                files[i].delete();
            }
        }

        //跳转地址带上oid参数
        attr.addAttribute("oid", oid);
        return "redirect:/user/toUpdateComment";
    }

    @RequestMapping("/user/addCommPic")
    public String addCommPic(String picid,MultipartFile file,HttpServletRequest request,RedirectAttributes attr) throws IOException {
        String filePath =request.getServletContext().getRealPath("/comment");
        File realPath = new File(filePath);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        String  fileName = UUID.randomUUID().toString().replaceAll("-","")+file.getOriginalFilename();;
        File targetFile = new File(filePath,fileName);
        file.transferTo(targetFile);
        orderService.addCommPic(picid,fileName);

        //跳转地址带上oid参数
        String oid = orderService.getOidByPicid(picid);
        attr.addAttribute("oid", oid);
        return "redirect:/user/toUpdateComment";

    }

    @RequestMapping("/user/deleteComment")
    public String deleteComment(String oid,HttpServletRequest request){
        Comment comment = orderService.getComment(oid);
        orderService.deleteComment(oid);
        orderService.deletePics(comment.getPicid());
        //删除图片
        String filePath =request.getServletContext().getRealPath("/comment");
        File realPath = new File(filePath);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        File[] files = realPath.listFiles();
        List<String> oldPics = comment.getPics();
        System.out.println(oldPics.get(1));
        for (int i = 0; i < oldPics.size(); i++){
            System.out.println("删除文件");
            for (int j = 0; j < files.length; j++) {
                //当该文件的名字和我们从数据库中查到的名字相同时删除
                if (files[j].getName().equals(oldPics.get(i))){
                    files[j].delete();
                }
            }

        }

        return "redirect:/user/allOrder";


    }

    @RequestMapping("/user/toUserInfo")
    public String toUserInfo(HttpSession session,Model model){
        User user = (User) session.getAttribute("loginInfo");
        UserInfo userInfo = userService.getUserInfo(user.getUid());
        model.addAttribute("userInfo",userInfo);
        return "jsp/userInfo";

    }

    @RequestMapping("/user/addUserInfo")
    public String addUserInfo(){
        return "redirect:/user/toUserInfo";
    }


    @RequestMapping("/user/updateUserInfo")
    public String updateUserInfo() {
        return "redirect:/user/toUserInfo";
    }



}
